package com.oktest.measure.ui.fragment.work

import android.graphics.Canvas
import android.os.Bundle
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.cali.common.kt.param
import com.cali.libcore.base.BaseFragment
import com.chad.library.adapter.base.listener.OnItemSwipeListener
import com.oktest.measure.MyApp
import com.oktest.measure.R
import com.oktest.measure.entity.Type
import com.oktest.measure.entity.WorkHistoryEntity
import com.oktest.measure.kt.TASK_COMPLETED
import com.oktest.measure.ui.adapter.HistoryTestSwipeAdapter
import kotlinx.android.synthetic.main.fragment_work_test_history.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * @Author hhh
 * @Date 2020/9/19
 */
class TestHistoryFragment :BaseFragment() {

    private val historyAdapter by lazy {
        HistoryTestSwipeAdapter().also {
            it.setOnItemClickListener { adapter, view, position ->
                val item = adapter.getItem(position) as WorkHistoryEntity
                val fragment = HistoryDetailFragment()
                    .param(HistoryDetailFragment.WORK_ID to item.taskId.toString())
                start(fragment)
            }
        }
    }

    private val onItemSwipeListener by lazy {
        object :OnItemSwipeListener{
            override fun clearView(viewHolder: RecyclerView.ViewHolder?, pos: Int) {
            }

            override fun onItemSwiped(viewHolder: RecyclerView.ViewHolder?, pos: Int) {
            }

            override fun onItemSwipeStart(viewHolder: RecyclerView.ViewHolder?, pos: Int) {
            }

            override fun onItemSwipeMoving(
                canvas: Canvas?,
                viewHolder: RecyclerView.ViewHolder?,
                dX: Float,
                dY: Float,
                isCurrentlyActive: Boolean
            ) {
                canvas?.drawColor(ContextCompat.getColor(context!!,R.color.red))
            }
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_work_test_history
    }

    override fun initData(savedInstanceState: Bundle?) {
        toolbarHelper?.apply {
            setTitleText("调试历史")
        }
        initRecyclerView()
    }

    private fun initRecyclerView() {
        historyRecyclerView.layoutManager = LinearLayoutManager(context)
        historyRecyclerView.adapter = historyAdapter
        historyAdapter.draggableModule.apply {
            isSwipeEnabled = true
            itemTouchHelperCallback.setSwipeMoveFlags(ItemTouchHelper.START)
            setOnItemSwipeListener(onItemSwipeListener)
        }
        getHistory()
    }

    override fun hasToolbar(): Boolean {
        return true
    }

    private fun getHistory() =  launch {
        showTip("正在加载")
        val list = arrayListOf<WorkHistoryEntity>()
        withContext(Dispatchers.IO){
            MyApp.roomDatabase.xmlDao().queryAll().forEach {
                val typeList = arrayListOf<Type>()
                val devices = MyApp.roomDatabase.xmlDao().devices(it.id)
                devices.forEach { device ->
                    typeList.addAll(MyApp.roomDatabase.deviceDao().types(device.id))
                }
                val done = typeList.filter { type ->
                    type.isDone()
                }.size
                val detail = MyApp.roomDatabase.homeTaskDetailDao().query(it.id.toString())
                val state = if(MyApp.currentTaskId == it.id) "调试中" else TASK_COMPLETED
                val entity = WorkHistoryEntity(
                    taskId = it.id,
                    taskName = it.name,
                    taskNum = devices.size,
                    overNum = done,
                    time = detail?.startupTime ?: "",
                    taskState = state
                )
                list.add(entity)
            }
        }
        historyAdapter.setList(list)
        dismissTip()
    }

    override fun onBackPressedSupport(): Boolean {
        pop()
        return true
    }

}